import React ,{useRef,useState,useEffect} from 'react';

// 使用useRef 获取dom元素得实例
export const UseRefn:React.FC = ()=>{
    const refInput = useRef<HTMLInputElement>(null);
    const getFocus = ()=>{
        refInput.current?.focus();
    }
    const getValue = ()=>{
        alert(refInput.current?.value)
    }
    return(
        <>
        <h1>获取dom元素得对象</h1>
        <input type="text" ref={refInput}  />
        <button onClick={getFocus}>点击获取交点</button>
        <button onClick={getValue}>获取内容值</button>
        </>
    )
}


// 使用useRef 保存组件得状态；
export const Counter:React.FC=()=>{
    const [count,setCount] = useState(0);
    const oldNumber = useRef<number>(); //只有组件第一次执行得时候才会调用 useRef
    const increaseFun = ()=>{
        setCount(e=>{
            return e+1;
        });
        oldNumber.current = count;
    }

    return(
        <>
        <h1>计数器</h1>
        <h2>最新值：{count}</h2>
        <h2>旧值：{oldNumber.current}</h2>
        <button onClick={increaseFun}>+1</button>
        <button onClick={()=>{setCount(count-1)}}>-1</button>
        </>
    )
}

// 注意点
// 1、组件rerender时useRef不会被重置初始化

export const RefTime:React.FC = ()=>{
    const [count,setCount] = useState(0);
    const times = useRef(Date.now());
    const increaseFun = ()=>{
        setCount(pre=>pre+1);
    }
    return(
        <>
        <h1>数值：{count};不会变化得时间：{times.current}</h1>
        <button onClick={increaseFun}>+1</button>
        </>
    )
}
// 2.ref.current 不能作为其它hooks得依赖项
//

export const RefTimeChange:React.FC = ()=>{
    const [count,setCount] = useState(0);
    const times = useRef(Date.now);
    const increaseFun = ()=>{
        setCount(pre=>pre+1);
    }
    const changeTime = ()=>{
        // times.current = Date.now();
        console.log(times.current)
    }

    useEffect(()=>{
        console.log('effect');
    },[times.current])
    return(
        <>
        <h1>数值：{count};不会变化得时间：</h1>
        <button onClick={increaseFun}>+1</button>
        <button onClick={changeTime}>想修改Time</button>
        </>
    )
}